package com.xksms.miniotest.service.imlp;

import com.xksms.miniotest.exception.ExceptionEnum;
import com.xksms.miniotest.utils.ImageUtil;
import com.xksms.miniotest.utils.MinioUtil;
import com.xksms.miniotest.utils.text.JsonResult;
import com.xksms.miniotest.service.UploadService;
import io.minio.Result;
import io.minio.StatObjectResponse;
import io.minio.messages.DeleteError;
import org.apache.commons.compress.utils.IOUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Objects;

/**
 * @ClassName uploadService
 * @Description TODO
 * @Author 程超
 * @Date 2022/8/4 8:35
 */
@Service
public class UploadServiceImpl implements UploadService {


    @Override
    public JsonResult<String> uploadWaterMarkImage(MultipartFile file, String bucket, String objectName, float quality, String positions, String waterMarkContent, String deductReason, String rgb, float alpha) throws Exception {
        MinioUtil.createBucket(bucket);
        String time = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH:mm:ss"));
        if (StringUtils.hasText(waterMarkContent)) {
            waterMarkContent = waterMarkContent + "\\" + time;
        } else {
            waterMarkContent = time;
        }
        File waterMark = ImageUtil.compressPic(file, quality, positions, waterMarkContent, rgb, alpha);
        String fileName = deductReason + "-" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")) + "." + Objects.requireNonNull(file.getContentType()).split("/")[1];
        String fileUrl = MinioUtil.uploadFile(waterMark, bucket, objectName, fileName);
        return JsonResult.success(null, fileUrl);
    }

    @Override
    public JsonResult uploadFiles(MultipartFile[] files, String bucket, String objectName) throws Exception {
        if (files.length == 0) {
            return JsonResult.error(ExceptionEnum.CONTENT_IS_EMPTY);
        }
        MinioUtil.createBucket(bucket);
        List<String> urls = MinioUtil.uploadFiles(files, bucket, objectName);
        return JsonResult.success(urls);
    }

    @Override
    public JsonResult downloadFile(String url, HttpServletResponse response) {
        if (!StringUtils.hasText(url)) {
            return JsonResult.error(ExceptionEnum.CONTENT_IS_EMPTY);
        }
        String[] split = url.split("/");
        //split[3]为桶名
        String objectName = url.split((split[3] + "/"))[1];
        InputStream inputStream;
        StatObjectResponse statObjectResponse;
        try {
            // 获取文件的输入流
            inputStream = MinioUtil.download(url);
            //获取对象信息和元数据
            statObjectResponse = MinioUtil.statObject(url);
            //获取文件名称  replace是因为文件名可能存在空格 URL中的空格有时候被编码成%20，有时候被编码成加号+
            String fileName = URLEncoder.encode(objectName.substring(objectName.lastIndexOf("/") + 1), "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ";" + "filename*=utf-8''" + fileName);
            //根据文件的类型设置文件ContentType类型
            response.setContentType(statObjectResponse.contentType());
            response.setCharacterEncoding("utf-8");
            IOUtils.copy(inputStream, response.getOutputStream());
            inputStream.close();
            return JsonResult.success();
        } catch (Exception e) {
            return JsonResult.error(ExceptionEnum.CONTENT_IS_EMPTY);
        }

    }

    @Override
    public JsonResult deleteFile(String url) {
        if (!StringUtils.hasText(url)) {
            return JsonResult.error(ExceptionEnum.CONTENT_IS_EMPTY);
        }
        try {
            MinioUtil.deleteObject(url);
        } catch (Exception e) {
            return JsonResult.error(ExceptionEnum.CONTENT_IS_EMPTY);
        }
        return JsonResult.success();
    }

    @Override
    public JsonResult deleteFiles(String[] urls) throws Exception {
        if (ObjectUtils.isEmpty(urls)) {
            return JsonResult.error(ExceptionEnum.CONTENT_IS_EMPTY);
        }
        Iterable<Result<DeleteError>> results = MinioUtil.deleteObjects(urls);
        for (Result<DeleteError> result : results) {
            DeleteError error = result.get();
            return JsonResult.error("删除失败： " + error.objectName() + "; 原因是：" + error.message());
        }
        return JsonResult.success();
    }

    @Override
    public JsonResult uploadFilesRename(MultipartFile[] files, String bucket, String objectName, String rename) {
        if (files.length == 0) {
            return JsonResult.error(ExceptionEnum.CONTENT_IS_EMPTY);
        }
        try {
            List<String> urls = MinioUtil.uploadFiles(files, bucket, objectName, rename);
            return   JsonResult.success(urls);
        } catch (Exception e) {
            e.printStackTrace();
            return  JsonResult.error();
        }
    }

    @Override
    public JsonResult getBucketConfig(String bucket) {
        if (!StringUtils.hasText(bucket)) {
            return JsonResult.error(ExceptionEnum.CONTENT_IS_EMPTY);
        }
        try {
            String bucketConfig = MinioUtil.getConfigByBucket(bucket);
            return JsonResult.success(bucketConfig);
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.error();
        }
    }

    @Override
    public JsonResult setBucketConfig(String bucket) {
        if (!StringUtils.hasText(bucket)) {
            return JsonResult.error(ExceptionEnum.CONTENT_IS_EMPTY);
        }
        try {
            MinioUtil.setConfigByBucket(bucket);
            return JsonResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.error();
        }
    }

    @Override
    public JsonResult uploadMarkImage(MultipartFile file, String bucket, String objectName, String waterMarkContent) throws Exception {
        waterMarkContent = ("主体：" +"diafmkea" + "\\" + "点位名称：" + "saasjd" + "\\" + "问题明细：" + "ajklma" )
                + "\\" + "时间：" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy年MM月dd日HH:mm:ss"));
        BufferedImage bufferedImage = ImageUtil.getTextWatermarkPic(file.getInputStream(), waterMarkContent, "ffffff");

        return null;
    }
}
